<?php
class doom_core_log {

    const LEVEL_ALL = 0;

    const LEVEL_DEBUG = 1;

    const LEVEL_ERROR = 2;

    const LEVEL_OFF = 255;

    public $_engine;

    public function getEngineConfig() {
        throw new Exception('需覆盖此方法:' . __METHOD__, 1);
    }

    public function getEngineClazz() {
        throw new Exception('需覆盖此方法:' . __METHOD__, 1);
    }

    public function formatLog($message, $callStack) {
        return date('[Y-m-d H:i:s]') . "[{$callStack['file']}:{$callStack['line']}]" . $message;
    }
    
    public function getLevel() {
        return doom_config::$LOG_LEVEL;
    }

    public function debug($message) {
        if (self::LEVEL_DEBUG >= $this->getLevel()) {
            $logStack = array();
            
            $callStack = debug_backtrace();
            $firstTrace = array_shift($callStack);
            
            $logStack['file'] = $firstTrace['file'];
            $logStack['line'] = $firstTrace['line'];
            $logStack['trace'] = array();
            self::_callTrace2errTrace($callStack, $logStack['trace']);
            
            $this->_engine->debug($this->formatLog($message, $logStack));
        }
    }

    public function error($message) {
        if (self::LEVEL_ERROR >= $this->getLevel()) {
            $logStack = array();
            
            $callStack = debug_backtrace();
            $firstTrace = array_shift($callStack);
            
            $logStack['file'] = $firstTrace['file'];
            $logStack['line'] = $firstTrace['line'];
            $logStack['trace'] = array();
            self::_callTrace2errTrace($callStack, $logStack['trace']);
            
            $this->_engine->error($this->formatLog($message, $logStack));
        }
    }
    
    /**
     * 将debug_backtrace()的结果转换为doom_core_error的trace
     * @param array $backTrace
     * @param array $errTrace:
     */
    static private function _callTrace2errTrace(&$backTrace, &$errTrace) {
        if (is_array($backTrace) && is_array($errTrace)) {
            foreach ($backTrace as &$bTrace) {
                $errTrace[] = array(
                        'file' => $bTrace['file'],
                        'line' => $bTrace['line'],
                        'class' => $bTrace['class'],
                        'function' => $bTrace['function'],
                        'type' => $bTrace['type']);
            }
        }
    }
}
//     const LEVEL_INFO = 0;
//     const LEVEL_WARN = 0;
//     const LEVEL_FATAL = 0;
?>